package jal4eclipse.ui.editors;

import jal4eclipse.jal.JALConstant;
import jal4eclipse.jal.JALParser;
import jal4eclipse.jal.structure.JMethod;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.eclipse.ui.IFileEditorInput;

public class JALAutoCompletHelper {
	static Map includesMap = null;
	private JALAutoCompletHelper() {}

	public static String[] getWords(String textToCurs,JALEditor editor) throws Exception{
		
		/*
		 * build include map 
		 */
		includesMap = FileUtil.getIncludes(editor);
		
		/*
		 * auto complete include
		 */
		textToCurs = textToCurs.trim();
		if (textToCurs.trim().toUpperCase().startsWith("INCLUDE")) {
				Set keySet = includesMap.keySet();
				return (String[]) keySet.toArray(new String[keySet.size()]);
		}
		
		
		
		/*
		 * other stuff 
		 */
		
		// find avaiable func / proc / vars
		IFileEditorInput input = (IFileEditorInput)editor.getEditorInput();
		File file = new File(input.getFile().getLocation().toOSString());
		
		Map all = new TreeMap();
		JALParser.buildTree(file,includesMap,all);
		
		/*
		 * Auto complete func and proc params 
		 */
		if (all.containsKey(textToCurs)) {
			
			if (all.get(textToCurs) instanceof JMethod) {
				JMethod elem= (JMethod) all.get(textToCurs);
				return new String[]{"("+elem.getParams()+")"};
			}
		}
		
		List allWords = new ArrayList();
		
		for(Iterator it = all.keySet().iterator();it.hasNext();){
			String name = (String)it.next();
			allWords.add(name);
		}
		for (int i =0;i<JALConstant.KEYWORDS.length;i++){
			allWords.add(JALConstant.KEYWORDS[i]);
		}
		for (int i =0;i<JALConstant.KEYWORDS2.length;i++){
			allWords.add(JALConstant.KEYWORDS2[i]);
		}
		for (int i =0;i<JALConstant.KEYWORDS3.length;i++){
			allWords.add(JALConstant.KEYWORDS3[i]);
		}
		for (int i =0;i<JALConstant.TYPES.length;i++){
			allWords.add(JALConstant.TYPES[i]);
		}
		
		return (String[]) allWords.toArray(new String[allWords.size()]);
	}
	
	
}
